/*
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-03 10:55:29
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Text,
  TouchableOpacity,
  PixelRatio,
  TextInput,
  Keyboard,
  ScrollView,
  NativeModules,
  Platform
} from 'react-native';
import { Button, msg } from '@/common';
import { uploadImage } from '@/config';
import api from '@/api';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorBlack,
  fontColorCoffee,
  screenWidth,
  px2dp,
  screenHeight,
  splitLineColorLightGray,
  fontColorSecDeepGray,
} from '@/styles';

const { Submit, SendButton } = Button;

export default class ContractSign extends Component {
  constructor(props) {
    super(props);
    this.state = {
      description: '', // 选择的特殊要求
      keyboardHeight: '', // 键盘高度
      isSubmit: false,
      code: ''
    };
  }

  componentDidMount() {
    if (Platform.OS == 'android') {
      // 监听键盘
      this.keyboardDidShowListener = Keyboard.addListener(
        'keyboardWillShow',
        this._keyboardDidShow.bind(this),
      );
      this.keyboardDidHideListener = Keyboard.addListener(
        'keyboardWillHide',
        this._keyboardDidHide.bind(this),
      );
    } else {
      NativeModules.BridgeManager.iOSIQKeyaboard(true);
    }
  }

  componentWillUnmount() {
    if (Platform.OS == 'android') {
      this.keyboardDidShowListener.remove();
      this.keyboardDidHideListener.remove();
    } else {
      NativeModules.BridgeManager.iOSIQKeyaboard(false);
    }
  }

  render() {
    const { contractData, routerFrom } = this.props;
    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          // msg.emit('router: back');
        }}
        onShow={() => { }}
      >
        <ScrollView style={styles.mask} />
        <View
          style={[
            styles.infoContainer,
            { marginBottom: Number(this.state.keyboardHeight) },
          ]}
        >
          <View style={styles.header}>
            <TouchableOpacity style={styles.cancel} onPress={this.cancel}>
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              签署授权
            </Text>
            <Submit
              text='确定'
              boxStyle={styles.submitBtn}
              btnTextStyle={styles.btnTextStyle}
              disabled={false}
              onClick={this.submit}
            />
          </View>
          {/* 备注 */}
          <View
            style={styles.editContainer}
            showsVerticalScrollIndicator={false}
          >
            {
              routerFrom == 'B2BMallOrderPay' ?
                <Text style={styles.tips}>
                  您正在进行合同签署操作，为保证采购安全，需进行短信校验，验证码已发送至用户手机号
                  <Text style={{ color: fontColorCoffee }}>{contractData.mobile}</Text>
                  ，请校验。
                </Text> :
                <Text style={styles.tips}>
                  请输入手机号
                  <Text style={{ color: fontColorCoffee }}>{contractData.mobile}</Text>
                  收到的
                </Text>
            }

            <View style={styles.codeWrap}>
              <TextInput
                style={[styles.textInput]}
                placeholder='验证码'
                maxLength={6}
                keyboardType='number-pad'
                placeholderTextColor='rgba(153, 151, 150, 1)'
                underlineColorAndroid='transparent'
                // clearButtonMode="while-editing"
                onChangeText={(text) => {
                  this.setState({
                    code: text,
                  });
                }}
              />
              <SendButton
                btnStyle={styles.sendBtn}
                onClick={() => this.sendMsgCode()}
                clickValid={() => {}}
                text='发送验证码'
              />
            </View>
          </View>
        </View>
      </Modal>
    );
  }

  sendMsgCode = () => {
    const { contractData } = this.props;
    api.contract.sendCode({ instId: contractData && (contractData.instanceId || contractData.id) }).then(res => {
      if (!res.success) {
        // onChange('contractSignIsShow', false)
        // NativeModules.WindowModule.showWindow({
        //   content: "验证码发送失败",
        //   onlyRightBtn: '1'
        // }, (e) => { })
        msg.emit('app:tip', { text: '验证码发送失败' });
      }
    });
  }

  _keyboardDidShow(e) {
    const { keyboardHeight } = this.state;
    if (keyboardHeight <= 0) {
      this.setState({
        keyboardHeight: e.startCoordinates.height,
      });
    }
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 改变
  onChangeText = (text) => {
    if (text.length > 50) {
      return;
    }
    this.setState({ description: text });
  };

  // 提交
  submit = () => {
    const { onChange, contractData, data } = this.props;
    const { code } = this.state;
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    if (!code) {
      msg.emit('app:tip', { text: '请输入验证码' });
      return;
    }
    // this.cancel();
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '合同签署中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    const xmParams = {
      instId: contractData.instanceId || contractData.id,
      code,
      userType: contractData.buyerType,
      custId: contractData.buyerId,
    };
    api.contract.verify(xmParams).then(res => {
      msg.emit('app:selfTip', { isVisible: false, text: '', icon: '' });
      if (res.success) {
        onChange('contractSignIsShow', false);
        msg.emit('router: goToNext', {
          routeName: 'ContractAutograph',
          routerFrom,
          data,
          instId: contractData.instanceId || contractData.id,
        });
      } else {
        msg.emit('app:selfTip', { isVisible: false, text: '', icon: '' });
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  cancel = () => {
    const { onChange } = this.props;
    onChange('contractSignIsShow', false);
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    // width: screenWidth,
    // height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    // position: 'absolute',
    flex: 1,
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.6 * screenHeight,
    backgroundColor: mainBgColorWhite,
    // position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },

  editContainer: {
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    height: px2dp(560),
  },
  codeWrap: {
    width: '100%',
    position: 'relative',
    marginTop: px2dp(24),
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(8),
  },
  sendBtn: {
    position: 'absolute',
    right: 0,
    height: px2dp(88),
    borderWidth: 0,
    backgroundColor: 'transparent'
  },
  textInput: {
    height: px2dp(88),
    paddingLeft: px2dp(8),
    color: fontColorBlack
  },
  tips: {
    fontSize: px2dp(28),
    color: fontColorBlack
  },
  submitBtn: {
    width: px2dp(104),
    height: px2dp(60),
    borderRadius: px2dp(8),
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    right: px2dp(28),
  },
  btnTextStyle: {
    fontSize: px2dp(32),
    color: fontColorCoffee,
  }
});
